package cn.tnar.parkservice.service.impl;


import cn.tnar.parkservice.config.Constant;
import cn.tnar.parkservice.config.ExceptionConst;
import cn.tnar.parkservice.exception.CustomException;
import cn.tnar.parkservice.mapper.TParkMemberGroupRelationMapper;
import cn.tnar.parkservice.mapper.TParkVisitHistoryMapper;
import cn.tnar.parkservice.model.dto.MemberinfoMqDto;
import cn.tnar.parkservice.model.dto.SyncMemberDto;
import cn.tnar.parkservice.model.dto.TParkMemberGroupRelationDto;
import cn.tnar.parkservice.model.dto.TParkVisitDto;
import cn.tnar.parkservice.model.entity.TCarFeesroleinfo;
import cn.tnar.parkservice.model.entity.TParkMemberGroup;
import cn.tnar.parkservice.model.entity.TParkMemberGroupRelation;
import cn.tnar.parkservice.model.entity.TParkVisitHistory;
import cn.tnar.parkservice.model.request.TParkVisistApproveRequest;
import cn.tnar.parkservice.model.request.TParkVisitHistoryRequest;
import cn.tnar.parkservice.model.response.*;
import cn.tnar.parkservice.service.*;
import cn.tnar.parkservice.util.DateUtils;
import cn.tnar.parkservice.util.DtoUtil;
import cn.tnar.parkservice.util.common.ResultCode;
import cn.tnar.parkservice.util.common.ResultJson;
import cn.tnar.parkservice.util.common.StringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zzb
 * @since 2019-08-28
 */
@Slf4j
@Service
public class TParkVisitHistoryServiceImpl extends ServiceImpl<TParkVisitHistoryMapper, TParkVisitHistory> implements ITParkVisitHistoryService {

    private Logger logger = LoggerFactory.getLogger(TParkVisitHistoryServiceImpl.class);

    private ResultJson resultJson = new ResultJson();

    @Autowired
    @Qualifier("tParkMemberGroupServiceImpl")
    private ITParkMemberGroupService itParkMemberGroupService;

    @Autowired
    @Qualifier("tCarFeesroleinfoServiceImpl")
    private ITCarFeesroleinfoService itCarFeesroleinfoService;

    @Autowired
    @Qualifier("tParkMemberGroupRelationServiceImpl")
    private ITParkMemberGroupRelationService itParkMemberGroupRelationService;

    @Autowired
    private TParkVisitHistoryMapper tParkVisitHistoryMapper;

    @Autowired
    private ITParkRegionService itParkRegionService;

    @Autowired
    private TParkMemberGroupRelationMapper tParkMemberGroupRelationMapper;

    @Autowired
    private MqService mqService;

    @Override
    public ResultJson select(String json) {
        TParkVisitHistoryRequest request = JSON.parseObject(json, TParkVisitHistoryRequest.class);
        TParkMemberGroup byId = itParkMemberGroupService.getById(request.getMemberGroupId());
        IPage<TParkVisitHistory> page = new Page<>();
        List<TParkVisitHistoryResponse> list = new ArrayList<>();
        //子卡时
        if (byId.getType() == 1) {
            List<String> memberIds = itParkMemberGroupRelationService.getVisitIdByChild(request.getMemberGroupId());

            page = getPage(memberIds, request);

            TCarFeesroleinfo byId1 = itCarFeesroleinfoService.getById(byId.getFeesroleinfoId());
            for (TParkVisitHistory entity : page.getRecords()) {
                TParkVisitHistoryResponse tParkVisitHistoryResponse = DtoUtil.convertObject(entity, TParkVisitHistoryResponse.class);
                tParkVisitHistoryResponse.setFeesroleinfoId(byId.getFeesroleinfoId());
                tParkVisitHistoryResponse.setFeesroleinfoName(byId1 == null ? "" : byId1.getRoleName());
                list.add(tParkVisitHistoryResponse);
            }

        }
        if (byId.getType() == 0) {
            //卡组时
            List<String> memberIds = itParkMemberGroupRelationService.getVisitIdByParent(request.getMemberGroupId());

            page = getPage(memberIds, request);

            for (TParkVisitHistory entity : page.getRecords()) {

                QueryWrapper<TParkMemberGroupRelation> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("member_id", entity.getId());
                TParkMemberGroupRelation one = itParkMemberGroupRelationService.getOne(queryWrapper);
                TParkMemberGroup groupById = itParkMemberGroupService.getById(one.getGroupId());
                TCarFeesroleinfo roleById = itCarFeesroleinfoService.getById(groupById.getFeesroleinfoId() == null ? "" : groupById.getFeesroleinfoId());
                TParkVisitHistoryResponse tParkVisitHistoryResponse = DtoUtil.convertObject(entity, TParkVisitHistoryResponse.class);
                tParkVisitHistoryResponse.setFeesroleinfoId(byId.getFeesroleinfoId());
                tParkVisitHistoryResponse.setFeesroleinfoName(roleById == null ? "" : roleById.getRoleName());
                list.add(tParkVisitHistoryResponse);
            }
        }

        Page<TParkVisitHistoryResponse> returnPag = new Page<>(request.getPageNo(), request.getPageSize());
        returnPag.setRecords(list);
        returnPag.setCurrent(page.getCurrent());
        returnPag.setSize(page.getSize());
        returnPag.setTotal(page.getTotal());
        returnPag.setPages(page.getPages());

        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(returnPag);
    }

    @Override
    @Transactional
    public ResultJson reserve(TParkVisitHistory requset) {
        logger.info("预约我入参：id= " + requset.getId() + " GroupId= " + requset.getGroupId() + " ApplyId= " + requset.getApplyId() + " ApplyStatus= " + requset.getApplyStatus());
        int id = requset.getId();
        String now = DateUtils.getNowString(DateUtils.YYYYMMDDHHMMSS);
        long customerVisitTime = requset.getCustomerVisitTime();
        long visitTimeStart = Long.valueOf(String.valueOf(customerVisitTime).substring(0, 8) + "000000");
        long visitTimeEnd = Long.valueOf(String.valueOf(customerVisitTime).substring(0, 8) + "235959");
        int applyStatus = requset.getApplyStatus();
        requset.setVisitTimeStart(visitTimeStart);
        requset.setVisitTimeEnd(visitTimeEnd);
        requset.setApplyTime(Long.valueOf(now));

        List<TParkVisitHistory> list = new ArrayList<>();
        boolean flag = false;
        if (id > 0) {
            // 修改
            flag = this.updateById(requset);
        } else {
            // 新增
            if (applyStatus == 2) {
                requset.setAccessTime(Long.valueOf(now));
            }
            flag = this.save(requset);
            QueryWrapper<TParkVisitHistory> wrapper = new QueryWrapper<>();
            wrapper.eq("park_code", requset.getParkCode());
            wrapper.eq("apply_mobile", requset.getApplyMobile());
            wrapper.eq("apply_status", applyStatus);
            wrapper.eq("mobile", requset.getMobile());
            wrapper.orderByDesc("id");
            list = this.list(wrapper);
            if (!StringUtils.isEmpty(requset.getGroupId()) && !list.isEmpty()) {
                this.saveOrUpdateMemRelation(list.get(0).getId(), requset.getGroupId(), now);
            }
        }
        if (flag) {
            // 预约我需要下发
            if (applyStatus == 2) {
                if (!list.isEmpty()) {
                    TParkVisitHistory tParkVisitHistory = list.get(0);
                    MemberinfoMqDto dto = new MemberinfoMqDto();
                    dto.setCar_id(tParkVisitHistory.getCarId());
                    dto.setCar_type(tParkVisitHistory.getCarType().toString());
                    dto.setEnd_date(String.valueOf(tParkVisitHistory.getVisitTimeEnd()));
                    QueryWrapper<TParkMemberGroupRelation> wp = new QueryWrapper<>();
                    wp.eq("member_id", tParkVisitHistory.getId());
                    wp.orderByDesc("id");
                    List<TParkMemberGroupRelation> list1 = itParkMemberGroupRelationService.list(wp);
                    String groupId = null != list1 && !list1.isEmpty() ? String.valueOf(list1.get(0).getGroupId()) : "";
                    dto.setGroup_id(String.valueOf(tParkVisitHistory.getId()));
                    dto.setId(String.valueOf(tParkVisitHistory.getId()));
                    dto.setMember_type(Constant.MEMBER_TYPE_VISIT);
                    dto.setOper_type(Constant.OPER_CAR);
                    dto.setOwner_name(tParkVisitHistory.getVisitor());
                    dto.setPark_code(tParkVisitHistory.getParkCode());
                    dto.setRemark(tParkVisitHistory.getRemarks());
                    dto.setSeat_num("0");
                    dto.setSend_time(now);
                    dto.setStart_date(String.valueOf(tParkVisitHistory.getVisitTimeStart()));
                    mqService.convertAndSend(Constant.EXCHANGE_NAME, "member." + tParkVisitHistory.getParkCode(), JSON.toJSONString(dto));
                    //下发关联关系
                    QueryWrapper<TParkMemberGroupRelation> wrapper = new QueryWrapper<>();
                    logger.info("下发卡组会员关联表 ：member_id= " + tParkVisitHistory.getId() + ";group_id =" + groupId);
                    wrapper.eq("member_id", tParkVisitHistory.getId());
                    wrapper.eq("group_id", groupId);
                    wrapper.last("limit 1");
                    TParkMemberGroupRelation relation = itParkMemberGroupRelationService.getOne(wrapper);
                    TParkMemberGroupRelationDto tParkMemberGroupRelationDto = new TParkMemberGroupRelationDto();
                    BeanUtils.copyProperties(relation, tParkMemberGroupRelationDto);
                    tParkMemberGroupRelationDto.setType(1);
                    mqService.convertAndSend(Constant.EXCHANGE_NAME, "memberGroupRelation." + tParkVisitHistory.getParkCode(), JSON.toJSONString(tParkMemberGroupRelationDto));

                }
            }
            resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG);
        } else {
            resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG);
        }
        return resultJson;
    }

    @Override
    public ResultJson updateReserve(TParkVisitHistory requset) {
        UpdateWrapper<TParkVisitHistory> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", requset.getId());
        boolean flag = this.update(requset, wrapper);
        if (flag) {
            resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG);
        } else {
            resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG);
        }
        return resultJson;
    }

    @Override
    public ResultJson applyHistory(TParkVisitDto requset) {
        String custId = requset.getCustId();
        int applyStatus = requset.getApplyStatus();
        String parkCode = requset.getParkCode();
        if (StringUtils.isBlank(custId) || applyStatus <= 0) {
            return resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG);
        }
        // 1: 待审核2: 已通过3: 未通过
        QueryWrapper wrapper = new QueryWrapper<>();
        wrapper.eq("apply_status", applyStatus);
        wrapper.eq("mobile", requset.getApplyMobile());
        if (!StringUtils.isBlank(parkCode)) {
            wrapper.eq("park_code", parkCode);
        }
        IPage<TParkVisitHistory> page = new Page<>();
        page.setSize(requset.getSize());
        page.setCurrent(requset.getPage());
        page = this.page(page, wrapper);
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(JSON.toJSON(page));
    }

    @Override
    public ResultJson visitHistory(TParkVisitDto requset) {
        String applyId = requset.getApplyId();
        int applyStatus = requset.getApplyStatus();
        String parkCode = requset.getParkCode();
        if (StringUtils.isBlank(applyId) && applyStatus == 0) {
            return resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG);
        }
        QueryWrapper<TParkVisitHistory> wrapper = new QueryWrapper<>();
        wrapper.eq("apply_status", applyStatus);
        wrapper.eq("apply_mobile", requset.getApplyMobile());
        if (!StringUtils.isBlank(parkCode)) {
            wrapper.eq("park_code", parkCode);
        }
        IPage<TParkVisitHistory> page = new Page<>();
        page.setSize(requset.getSize());
        page.setCurrent(requset.getPage());
        page = this.page(page, wrapper);
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(JSON.toJSON(page));
    }


    /**
     * 获取访客申请记录列表
     *
     * @param request
     * @return
     */
    @Override
    public ResultJson queryVisiterReocrd(TParkVisitHistoryRequest request) {
        Integer pageNo = request.getPageNo();
        Integer pageSize = request.getPageSize();
        Page<VisistRecordResponse> page = new Page<>(pageNo, pageSize);
        List<VisistRecordResponse> list = tParkVisitHistoryMapper.queryVisiterReocrd(page, request);
        list.forEach(map -> {
            Long groupId = map.getGroupId();
            List<String> region = getRegion(groupId);
            map.setRegionNames(region);
        });
        page.setRecords(list);
        return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(page);
    }

    /**
     * 获取访客卡证及区域信息
     *
     * @param parkCode
     * @return
     */
    @Override
    public ResultJson getVisitCard(String parkCode) {
        List<TParkMemberCardResponse> list = tParkVisitHistoryMapper.getVisitCard(parkCode);
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(tParkMemberCardResponse -> {
                Long id = tParkMemberCardResponse.getId();
                List<String> regionNames = getRegion(id);
                if (!CollectionUtils.isEmpty(regionNames)) {
                    tParkMemberCardResponse.setRegionNames(regionNames);
                }
            });
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(list);
        }
        return new ResultJson().setCode(ResultCode.FAIL).setMsg(ExceptionConst.ERROR_RECORD_NOT_FOUND).setData(null);
    }

    /**
     * 访客审核 ，拒绝 ，撤销通过
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResultJson visiterApprove(TParkVisistApproveRequest request) {
        TParkVisitHistory tParkVisitHistory = tParkVisitHistoryMapper.selectById(request.getId());
        String now = DateUtils.getNowString(DateUtils.YYYYMMDDHHMMSS);
        if (tParkVisitHistory.getApplyStatus() == request.getStatus()) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ExceptionConst.DON_NOT_OPERA_REPEAT).setData(false);
        }
        tParkVisitHistory.setApplyStatus(request.getStatus());
        tParkVisitHistory.setAccessTime(Long.valueOf(now));
//        tParkVisitHistory.setGroupId(request.getGroupId().toString());
        // 1:撤回 2:通过 3:拒绝
        if (request.getStatus() == 1) {
            //撤回 修改状态 撤销关联
            tParkVisitHistory.setGroupId(tParkVisitHistory.getGroupId());
            QueryWrapper<TParkMemberGroupRelation> qw = new QueryWrapper<>();
            qw.eq(request.getId() != null, "member_Id", request.getId());
            qw.eq(request.getGroupId() != null, "group_id", request.getGroupId());
            tParkMemberGroupRelationMapper.delete(qw);
        }
        if (request.getStatus() == 2) {
            //通过 修改状态 新增关联  新增有效期,卡组id
            String groupId = request.getGroupId().toString();

            //卡组下所有访客车牌 除当前车牌
            List<String> cars = tParkMemberGroupRelationMapper.getCarByChild(groupId, request.getId(), tParkVisitHistory.getCarId());
            if (cars != null && cars.size() > 0) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_CAR_MAX).setData(null);
            }

            tParkVisitHistory.setGroupId(groupId);
            tParkVisitHistory.setVisitTimeStart(Long.valueOf(request.getBeginTime()));
            tParkVisitHistory.setVisitTimeEnd(Long.valueOf(request.getEndTime()));
            TParkMemberGroupRelation relation = new TParkMemberGroupRelation();
            Long nowTime = Long.valueOf(now);
            relation.setGroupId(request.getGroupId());
            relation.setMemberId(request.getId());
            relation.setCreateTime(nowTime);
            relation.setUpdateTime(nowTime);
            tParkMemberGroupRelationMapper.insert(relation);
        }
        if (request.getStatus() == 3) {
            //拒绝 修改状态 新增原因
            tParkVisitHistory.setReason(request.getReason());
        }
        tParkVisitHistory.setOperId(request.getOperId());
        tParkVisitHistoryMapper.updateById(tParkVisitHistory);
        try {
            MemberinfoMqDto dto = new MemberinfoMqDto();
            dto.setCar_id(tParkVisitHistory.getCarId());
            dto.setCar_type(tParkVisitHistory.getCarType().toString());
            dto.setEnd_date(String.valueOf(tParkVisitHistory.getVisitTimeEnd()));
            dto.setGroup_id(request.getId().toString());
            dto.setId(request.getId().toString());
            dto.setMember_type(Constant.MEMBER_TYPE_VISIT);
            if (request.getStatus() == 2) {
                dto.setOper_type(Constant.OPER_CAR);
            }
            if (request.getStatus() == 1) {
                dto.setOper_type(Constant.OPER_DELETE);
            }
            dto.setOwner_name(tParkVisitHistory.getVisitor());
            dto.setPark_code(tParkVisitHistory.getParkCode());
            dto.setRemark(tParkVisitHistory.getRemarks());
            dto.setSeat_num("0");
            dto.setSend_time(now);
            dto.setStart_date(String.valueOf(tParkVisitHistory.getVisitTimeStart()));
            mqService.convertAndSend(Constant.EXCHANGE_NAME, "member." + tParkVisitHistory.getParkCode(), JSON.toJSONString(dto));
            //下发关联关系
            TParkMemberGroupRelationDto tParkMemberGroupRelationDto = new TParkMemberGroupRelationDto();
            tParkMemberGroupRelationDto.setGroupId(request.getGroupId());
            tParkMemberGroupRelationDto.setMemberId(request.getId());
            if (request.getStatus() == 2) {
                tParkMemberGroupRelationDto.setType(1);
            } else if (request.getStatus() == 1) {
                tParkMemberGroupRelationDto.setType(2);
            }
            mqService.convertAndSend(Constant.EXCHANGE_NAME, "memberGroupRelation." + tParkVisitHistory.getParkCode(), JSON.toJSONString(tParkMemberGroupRelationDto));

        } catch (Exception e) {
            log.error(ExceptionConst.AMQP_ERROR + e.getMessage());
            throw new CustomException(ExceptionConst.ERROR_APPROVE_DEFAULT);
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(true);
    }


    @Override
    @Transactional
    public ResultJson checkIn(TParkVisitDto requset) {
        int id = requset.getId();
        int applyStatus = requset.getApplyStatus();
        String operId = requset.getOperId();
        String groupId = requset.getGroupId();
        if (id == 0 || applyStatus == 0 || StringUtils.isBlank(operId) || StringUtils.isBlank(groupId)) {
            return resultJson.setCode(ResultCode.MISS_PARAM).setMsg(ResultCode.MISS_PARAM_MSG);
        }
        TParkVisitHistory apply = new TParkVisitHistory();
        apply.setId(id);
        apply.setApplyStatus(applyStatus);
        apply.setOperId(operId);
        // 1: 待审核2: 已通过3: 未通过
        String now = DateUtils.getNowString(DateUtils.YYYYMMDDHHMMSS);
        if (applyStatus == 2) {
            //卡组下所有访客车牌 除当前车牌
            List<String> cars = tParkMemberGroupRelationMapper.getCarByChild(groupId, Long.valueOf(id), tParkVisitHistoryMapper.selectById(id).getCarId());
            if (cars != null && cars.size() > 0) {
                return resultJson.setCode(ResultCode.FAIL).setMsg(Constant.MSG_CAR_MAX).setData(null);
            }

            apply.setAccessTime(Long.valueOf(now));
        }
        boolean flag = tParkVisitHistoryMapper.checkIn(apply);
        boolean flag1 = this.saveOrUpdateMemRelation(id, groupId, now);
        if (!flag || !flag1) {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG);
        } else {
            TParkVisitHistory tParkVisitHistory = new TParkVisitHistory();
            tParkVisitHistory = this.getById(id);
            if (tParkVisitHistory != null) {
                MemberinfoMqDto dto = new MemberinfoMqDto();
                dto.setCar_id(tParkVisitHistory.getCarId());
                dto.setCar_type(tParkVisitHistory.getCarType().toString());
                dto.setEnd_date(String.valueOf(tParkVisitHistory.getVisitTimeEnd()));
                dto.setGroup_id(String.valueOf(id));
                dto.setId(String.valueOf(id));
                dto.setMember_type(Constant.MEMBER_TYPE_VISIT);
                if (applyStatus == 2) {
                    dto.setOper_type(Constant.OPER_CAR);
                }
                if (applyStatus == 3) {
                    dto.setOper_type(Constant.OPER_DELETE);
                }
                dto.setOwner_name(tParkVisitHistory.getVisitor());
                dto.setPark_code(tParkVisitHistory.getParkCode());
                dto.setRemark(tParkVisitHistory.getRemarks());
                dto.setSeat_num("0");
                dto.setSend_time(now);
                dto.setStart_date(String.valueOf(tParkVisitHistory.getVisitTimeStart()));
                mqService.convertAndSend(Constant.EXCHANGE_NAME, "member." + tParkVisitHistory.getParkCode(), JSON.toJSONString(dto));

                //下发关联关系
                QueryWrapper<TParkMemberGroupRelation> wrapper = new QueryWrapper<>();
                wrapper.eq("member_id", id);
                wrapper.eq("group_id", groupId);
                wrapper.last("limit 1");
                TParkMemberGroupRelation relation = itParkMemberGroupRelationService.getOne(wrapper);
                TParkMemberGroupRelationDto tParkMemberGroupRelationDto = new TParkMemberGroupRelationDto();
                BeanUtils.copyProperties(relation, tParkMemberGroupRelationDto);
                if (applyStatus == 2) {
                    tParkMemberGroupRelationDto.setType(1);
                } else if (applyStatus == 3) {
                    tParkMemberGroupRelationDto.setType(3);
                }
                mqService.convertAndSend(Constant.EXCHANGE_NAME, "memberGroupRelation." + tParkVisitHistory.getParkCode(), JSON.toJSONString(tParkMemberGroupRelationDto));

            }
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG);
        }
    }

    public boolean saveOrUpdateMemRelation(int id, String groupId, String time) {
        QueryWrapper<TParkMemberGroupRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", id);
        wrapper.eq("group_id", groupId);
        int i = itParkMemberGroupRelationService.count(wrapper);
        boolean flag = false;
        if (i > 0) {
            flag = tParkVisitHistoryMapper.updateMemRelation(id, groupId, time);
        } else {
            flag = tParkVisitHistoryMapper.saveMemRelation(id, groupId, time);
        }
        return flag;
    }

    @Override
    public ResultJson cancel(TParkVisitDto requset) {
        int id = requset.getId();
        int applyStatus = requset.getApplyStatus();
        String operId = requset.getOperId();
        boolean flag = tParkVisitHistoryMapper.cancel(id, applyStatus, operId);
        if (flag) {
            return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG);
        } else {
            return resultJson.setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG);
        }
    }

    @Override
    public ResultJson queryBindCard(TParkVisitDto requset) {
        // 查询会员信息（访客表）
        TParkVisitHistory tParkVisitHistory = this.getById(requset.getId());
        // 查询 卡组id
        QueryWrapper<TParkMemberGroupRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("member_id", requset.getId());
        wrapper.eq("create_time", tParkVisitHistory.getAccessTime());
        TParkMemberGroupRelation relation = itParkMemberGroupRelationService.getOne(wrapper);
        VisitCardResponse card = new VisitCardResponse();
        if (null != relation) {
            // 查询卡组信息
            TParkMemberGroup member = itParkMemberGroupService.getById(relation.getGroupId());
            String regionCode = member.getRegionCode();
            card.setId(member.getId());
            card.setNo(member.getNo());
            card.setName(member.getName());
            if (!StringUtils.isBlank(regionCode)) {
                QueryWrapper ew = new QueryWrapper();
                List<RegionInfo> regionList = new ArrayList<>();
                // String regionCode 转list
                String[] regionArr = regionCode.split(",");
                List<String> regions = new ArrayList<>();
                regions = Arrays.asList(regionArr);
                ew.in("region_code", regions);
                regionList = itParkRegionService.list(ew);
                card.setRegion(regionList);
            }
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(JSON.toJSON(card));
    }

    /**
     * 修改访客车来访状态
     *
     * @param param
     * @return
     */
    @Override
    public ResultJson updateStatus(Map<String, Object> param) {
        String carId = param.get("carId").toString();
        Integer visitStatus = (Integer) param.get("visitStatus");
        Integer id = (Integer) param.get("id");
        QueryWrapper<TParkVisitHistory> qw = new QueryWrapper<>();
        qw.eq("car_id", carId);
        qw.eq("apply_status", 2);
        qw.eq("id", id);
        TParkVisitHistory tParkVisitHistory = tParkVisitHistoryMapper.selectOne(qw);
        if (tParkVisitHistory != null) {
            tParkVisitHistory.setVisitState(visitStatus);
        } else {
            throw new CustomException("该条数据不存在");
        }
        int count = tParkVisitHistoryMapper.update(tParkVisitHistory, qw);
        if (count > 0) {
            return new ResultJson().setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(true);
        } else {
            return new ResultJson().setCode(ResultCode.FAIL).setMsg(ResultCode.FAIL_MSG).setData(false);
        }
    }


    @Override
    public ResultJson queryCard(String parkCode) {
        QueryWrapper<TParkMemberGroup> wrapper = new QueryWrapper<>();
        wrapper.eq("park_code", parkCode);
        wrapper.eq("classify", 2);
        wrapper.eq("type", 1);
        wrapper.eq("del_flag", 0);
        List<TParkMemberGroup> list = itParkMemberGroupService.list(wrapper);
        List<VisitCardResponse> respList = new ArrayList<>();
        for (TParkMemberGroup member : list) {
            String regionCode = member.getRegionCode();
            VisitCardResponse card = new VisitCardResponse();
            card.setId(member.getId());
            card.setNo(member.getNo());
            card.setName(member.getName());
            if (!StringUtils.isBlank(regionCode)) {
                QueryWrapper ew = new QueryWrapper();
                List<RegionInfo> regionList = new ArrayList<>();
                // String regionCode 转list
                String[] regionArr = regionCode.split(",");
                List<String> regions = new ArrayList<>();
                regions = Arrays.asList(regionArr);
                ew.in("region_code", regions);
                regionList = itParkRegionService.list(ew);
                card.setRegion(regionList);
            }
            respList.add(card);
        }
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(JSON.toJSON(respList));
    }

    private IPage<TParkVisitHistory> getPage(List<String> memberIds, TParkVisitHistoryRequest request) {
        IPage<TParkVisitHistory> page1 = new Page<>();
        if (memberIds.size() > 0) {
            QueryWrapper<TParkVisitHistory> queryWrapper = new QueryWrapper<>();
            queryWrapper.between(StringUtils.isNotBlank(request.getStartTime() == null ? "" : request.getStartTime().toString()) && StringUtils.isNotBlank(request.getEndTime() == null ? "" : request.getEndTime().toString()), "visit_time_start", request.getStartTime() + "000000", request.getEndTime() + "235959");
            queryWrapper.like(StringUtils.isNotBlank(request.getCarId()), "car_id", request.getCarId());
            queryWrapper.eq(request.getVisitState() != null, "visit_state", request.getVisitState());
            queryWrapper.eq("apply_status", 2);
            queryWrapper.in("id", memberIds);
            IPage<TParkVisitHistory> page = new Page<>(request.getPageNo(), request.getPageSize());
            page1 = this.page(page, queryWrapper);
        }
        return page1;
    }

    /**
     * 根据卡证id查询区域信息
     * @param groupId
     * @return
     */
    private List<String> getRegion(Long groupId) {
        TParkMemberGroup tParkMemberGroup = itParkMemberGroupService.getById(groupId);
        List<String> regionNames = new ArrayList<>();
        if (tParkMemberGroup != null) {
            String regionCode = tParkMemberGroup.getRegionCode();
            if (StringUtil.isNotBlank(regionCode)) {
                String[] regionCodes = regionCode.split(",");
                List<Map<String, Object>> regionInfo = tParkVisitHistoryMapper.getRegionInfo(regionCodes);
                regionNames = regionInfo.stream().map(map -> (String) map.get("name")).collect(Collectors.toList());
                return regionNames;
            }
        }
        return regionNames;
    }


    @Override
    public ResultJson combineVisit(String parkCode) {
        SyncMemberDto dto = new SyncMemberDto();

        List<MemberinfoMqDto> members = new ArrayList<>();
        List<TParkMemberGroupRelationDto> memberGroupRelationsResult = new ArrayList<>();
        List<TParkMemberGroupRelationDto> memberGroupRelations = new ArrayList<>();
        QueryWrapper<TParkMemberGroup> tParkMemberGroupQueryWrapper = new QueryWrapper<>();
        tParkMemberGroupQueryWrapper.eq("park_code", parkCode);
        tParkMemberGroupQueryWrapper.eq("type", 1);
        tParkMemberGroupQueryWrapper.eq("classify", 2);
        tParkMemberGroupQueryWrapper.eq("del_flag", 0);

        List<TParkMemberGroup> memberGroupIds = itParkMemberGroupService.list(tParkMemberGroupQueryWrapper);
        if (memberGroupIds != null && memberGroupIds.size() > 0) {
            for (int i = 0; i < memberGroupIds.size(); i++) {
                List<TParkMemberGroupRelationDto> relation = tParkMemberGroupRelationMapper.getRelation(memberGroupIds.get(i).getId());
                if (relation != null && relation.size() > 0) {
                    for (int j = 0; j < relation.size(); j++) {
                        Map<String,Object> visit = tParkMemberGroupRelationMapper.getVisit(relation.get(j).getMemberId());
                        if (visit != null) {
                            MemberinfoMqDto memberinfoMqDto=new MemberinfoMqDto();
                            memberinfoMqDto.setCar_id(String.valueOf(visit.get("car_id")));
                            memberinfoMqDto.setCar_type(String.valueOf(visit.get("car_type")));
                            memberinfoMqDto.setEnd_date(String.valueOf(visit.get("end_date")));
                            memberinfoMqDto.setGroup_id(String.valueOf(visit.get("group_id")));
                            memberinfoMqDto.setId(String.valueOf(visit.get("id")));
                            memberinfoMqDto.setMember_type(String.valueOf(visit.get("member_type")));
                            memberinfoMqDto.setOper_type(String.valueOf(visit.get("oper_type")));
                            memberinfoMqDto.setOwner_name(String.valueOf(visit.get("owner_name")));
                            memberinfoMqDto.setPark_code(String.valueOf(visit.get("park_code")));
                            memberinfoMqDto.setRemark(String.valueOf(visit.get("remark")));
                            memberinfoMqDto.setSeat_num(String.valueOf(visit.get("seat_num")));
                            memberinfoMqDto.setSend_time(String.valueOf(visit.get("send_time")));
                            memberinfoMqDto.setStart_date(String.valueOf(visit.get("start_date")));

                            members.add(memberinfoMqDto);
                        }

                    }
                    memberGroupRelations.addAll(relation);
                }
            }
        }

        for (MemberinfoMqDto m : members) {
            for (TParkMemberGroupRelationDto t : memberGroupRelations) {
                  if(m.getId().equals(t.getMemberId().toString())){
                      memberGroupRelationsResult.add(t);
                  }
            }
        }


        dto.setMembers(members);
        dto.setMemberGroupRelations(memberGroupRelationsResult);
        return resultJson.setCode(ResultCode.SUCCESS).setMsg(ResultCode.SUCCESS_MSG).setData(dto);
    }


}
